import React from 'react'
import {connect} from 'react-redux'
import {messages} from "share/common";
import { Select, Button, Input, Badge, message, Popover } from 'antd'
import auditOpinionService from 'containers/finance-setting/audit-opinion/audit-opinion.service'
import 'styles/finance-setting/audit-opinion/audit-opinion.scss'
import debounce from 'lodash.debounce'
import NewOpinion from 'containers/finance-setting/audit-opinion/new-opinion'
import SlideFrame from  'components/slide-frame'
import ResizeTable from 'components/resize-table'
import EditOpinion from 'containers/finance-setting/audit-opinion/edit-opinion'
import menuRoute from 'routes/menuRoute'
const Option = Select.Option;
const Search = Input.Search;

class AuditOpinion extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      setOfBooksId: [],
      onSetOfBooksId: this.props.company.setOfBooksId,
      onLoad: false,
      offLoad: false,
      columns: [
        {title: messages('common.sequence')/*序号*/, dataIndex: 'index', render: (value, record, index) => this.state.size * this.state.page + index + 1},
        {title: messages('finance-setting.key64'/*审核意见*/), dataIndex: 'reply', width:'40%', render: value => <Popover content={value} placement='topLeft'>{value}</Popover>},
        {title: messages('finance-setting.key499'/*审核意见编码*/), dataIndex: 'code', width:'40%' },
        {title: messages('common.column.status')/*状态*/, dataIndex: 'status', render: value => { return value === 1000 ? <Badge text={messages('common.status.enable')/*启用*/} status={'success'}/> : <Badge text={messages('common.status.disable')/*禁用*/} status={'error'}/>}},
        {title: messages('common.operation')/*操作*/, width: 100, dataIndex: 'operation', render: (value, record) => <div>
          <a onClick={() => this.showEdit(record)}>{messages('common.edit')/*编辑*/}</a>
          <a style={{ marginLeft: 10 }} onClick={() => this.gotoDetail(record)}>{messages('common.detail')/*详情*/}</a>
        </div>}
      ],
      data: [],
      tableLoading: false,
      pagination: {
        total: 0,
      },
      page: 0,
      size: 10,
      rowSelection: {
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      selectedDataIds: [],
      searchValue: '',
      slideShow: false,
      editSlideShow: false,
      content: {},
      auditOpinionDetail:  menuRoute.getRouteItem('audit-opinion-detail'),    // 审核意见详情
    };
    this.handleSearch = debounce(this.handleSearch, 500);
  }

  componentWillMount() {
    this.getSetOfBook();
    this.handleChangeKey();
  };

  //获取帐套
  getSetOfBook = () => {
    auditOpinionService.getSetOfBooksByTenant().then(res => {
      this.setState({setOfBooksId:res.data})
    }).catch(() => {
      message.error(messages('finance-setting.key65'/*出错了*/));
    })
  };

  //选择项改变触发事件
  onSelectChange = (selectedRowKeys) => {
    const { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  //点击选择
  onSelectItem = (record, selected) => {
    let {selectedDataIds, rowSelection} = this.state;
    if(!selected){
      selectedDataIds.map((select, index) => {
        if( select.id === record.id ){
          selectedDataIds.splice(index, 1);
        }
      })
    } else {
      selectedDataIds.push(record);
    }
    this.setState({ selectedDataIds ,rowSelection:rowSelection});
  };

  //全选
  onSelectAll = (selected, selectedRows, changeRows) => {
    let {selectedDataIds} = this.state;
    if(!selected){
      changeRows.map(record => {
        selectedDataIds.map((select, index) => {
          if( select.id === record.id ){
            selectedDataIds.splice(index, 1);
          }
        })
      });
    } else {
      selectedRows.map(item => {
        let isContainer = false;
        selectedDataIds.map(select => {
          if( select.id === item.id ){
            isContainer = true;
          }
        });
        !isContainer && (selectedDataIds.push(item));
      });
    }
    this.setState({selectedDataIds});
  };

  //帐套更换
  handleChangeBookId = (value) => {
    this.setState({onSetOfBooksId: value},() => {
      this.handleChangeKey();
    });
  };

  //新建审核意见
  newOpinion = () => {
    this.setState({slideShow: true});
  };

  //启用/禁用审核意见
  handleOnOrOff = (e) => {
    let isOn = false;
    e.target.id === 'on' && (isOn = true);
    const { selectedDataIds } = this.state;
    let ids = [];
    selectedDataIds.map(item => {
      ids.push(item.id);
    });
    let params = {
      ids:ids,
      statusEnum: isOn ? 'USING' : 'DELETED'
    };
    auditOpinionService.onOrOffReply(params).then(() => {
      this.handleChangeKey();
    }).catch(() => {
      message.error(messages('finance-setting.key65'/*出错了*/));
    })
  };

  //搜索
  handleChangeKey = (e) => {
    let value = e ? e.target.value : this.state.searchValue;
    const {onSetOfBooksId, page, size} = this.state;
    if (value.length > 100) {
      message.error(messages('finance-setting.key145')/*最多输入100个字符*/);
      value = value.substr(0,100);
    }
    this.setState({tableLoading: true, searchValue: value}, () => {
      this.refs.searchInput.focus();
    });
    let params = {
      setOfBooksId: onSetOfBooksId,
      page,
      size,
      searchParam: value
    };
    this.handleSearch(params);
  };

  handleSearch = (params) => {
    const { page } = this.state;
    auditOpinionService.getReplyList(params).then(res => {
      this.setState({
        data: res.data.rows,
        tableLoading: false,
        pagination: {
          total: res.data.total,
          onChange: this.onChangePager,
          current: page + 1
        }
      })
    }).catch(() => {
      message.error(messages('finance-setting.key65'/*出错了*/))
    });
  };

  //分页
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.handleChangeKey();
      })
  };

  showEdit = (record) => {
    this.setState({
      editSlideShow: true,
      content: record
    });
  };

  gotoDetail = (record) => {
    this.context.router.push({
      pathname: this.state.auditOpinionDetail.url.replace(':id', record.setOfBooksId),
      state: { ruleInfo:record }
    });
  }

  render(){
    const { setOfBooksId, onLoad, offLoad, columns, data, pagination, tableLoading, rowSelection, slideShow,
      onSetOfBooksId, selectedDataIds, searchValue, content, editSlideShow } = this.state;
    return(
      <div className="audit-opinion">
        <div className="audit-opinion-title">{messages('finance-setting.key66'/*帐套：*/)}
          <Select onChange={e => this.handleChangeBookId(e)} defaultValue={`${this.props.company.setOfBooksName}`} disabled={!this.props.tenantMode}>
            {
              setOfBooksId.map(item => {
                return <Option key={item.id} title={item.setOfBooksName}>{item.setOfBooksName}</Option>
              })
            }
          </Select>
        </div>
        <div className="audit-opinion-operate">
          <Button type='primary' size='large' onClick={this.newOpinion} disabled={!this.props.tenantMode}>{messages('finance-setting.key67'/*新建审核意见*/)}</Button>
          <Search
            onChange={this.handleChangeKey}
            ref={'searchInput'}
            value={searchValue}
            style={{ display: 'block', float: 'right', width: '400px', top: '50%', marginTop: '-16px' }}
            placeholder={messages('finance-setting.key500'/*请输入审核意见项或审核意见编码*/)}
          />
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          bordered
          size={'middle'}
          // rowSelection={rowSelection}
          pagination={pagination}
          loading={tableLoading}
        />
        <SlideFrame show={slideShow}
                    title={messages('finance-setting.key67'/*新建审核意见*/)}
                    hasFooter={true}
                    hasMask={true}
                    params={{
                      slideShow,
                      setOfBooksId: onSetOfBooksId,
                      mode: 'father'
                    }}
                    content={NewOpinion}
                    onClose={(isRefresh) => {
                      this.setState({slideShow: false});
                      isRefresh === true && this.handleChangeKey();
                    }}
                    afterClose={(isRefresh) => {
                      this.setState({slideShow: false});
                      isRefresh === true && this.handleChangeKey();
                    }}/>
        <SlideFrame show={editSlideShow}
                    title={messages('finance-setting.key497'/*编辑审核意见*/)}
                    hasFooter={true}
                    hasMask={true}
                    params={{
                      editSlideShow,
                      content: content
                    }}
                    content={EditOpinion}
                    onClose={(isRefresh) => {
                      this.setState({editSlideShow: false});
                      isRefresh === true && this.handleChangeKey();
                    }}
                    afterClose={(isRefresh) => {
                      this.setState({editSlideShow: false});
                      isRefresh === true && this.handleChangeKey();
                    }}/>
      </div>
    )
  }
}

AuditOpinion.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state){
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(AuditOpinion);
